﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ShareMarking.Systems.Service;
using ShareMarking.Service;
using ShareMarking.Entity;
using System.Data;
using MySoft.Data;
using Common.Utilities.Excel.Export;
using System.IO;
using Common.Utilities.Excel;

namespace ShareMarking.Web.admin.EnterPrise.Activity
{
    public partial class List : ManagePage
    {
        #region 参数配置=================================

        protected int totalCount;
        protected int page;
        protected string A_Name = string.Empty;//活动名称
        protected string A_Manager = string.Empty;//活动负责人
        protected string pageSizeCookieKey = "qr_Activity_index_page_size";//当前页的每页大小的cookiekey
        protected int pageSize
        {
            get
            {
                int _default_size = 10;
                int _pagesize;
                if (int.TryParse(Utils.GetCookie(pageSizeCookieKey), out _pagesize))
                {
                    if (_pagesize > 0)
                    {
                        return _pagesize;
                    }
                }
                return _default_size;
            }
        }
        protected string orderBy = "qr_Activity.ActivityID desc";

        protected string keywords = string.Empty;
        protected string searchURL { get { return Utils.CombUrlTxt("List.aspx", "A_Name={0}&A_Manager={1}", this.A_Name,this.A_Manager); } }

        #endregion

        #region 初始化===================================

        protected void Page_Load(object sender, EventArgs e)
        {
            //检查权限
            //ChkAdminLevel("user_list", ShareMarkingEnums.ActionEnum.View.ToString());

            //初始化搜索参数
            this.keywords = DTRequest.GetQueryString("keywords");
            this.A_Name = DTRequest.GetQueryString("A_Name");
            this.A_Manager = DTRequest.GetQueryString("A_Manager");
            //this.A_wxQrCodeID = DTRequest.GetQueryInt("A_wxQrCodeID");
            if (!Page.IsPostBack)
            {
                //绑定下拉框的值

                //绑定列表
                RptBind();
            }
        }

        #endregion

        #region 绑定下拉框===============================

        #endregion

        #region 绑定列表=================================
        private void RptBind()
        {
            this.page = DTRequest.GetQueryInt("page", 1);
            
            //获取数据源            
            if (!A_Name.IsNullOrEmpty())
            {
                this.txtA_Name.Text = A_Name;
            }
            if (!A_Manager.IsNullOrEmpty())
            {
                this.txtA_Manager.Text = A_Manager;
            }
            
            this.rptList.DataSource = qr_ActivityService.Instance.Get_qr_Activity_PageSelect(page, pageSize, orderBy, out totalCount,A_Name,A_Manager);
            this.rptList.DataBind();

            //绑定页码
            txtPageNum.Text = this.pageSize.ToString();
            string pageUrl = ComLib.UrlHelper.Instance.SetUrl(searchURL).AddParam("page", "__id__").GetAddedParamUrl();
            PageContent.InnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
        }
        #endregion

        #region 搜索操作=================================

        //关健字查询
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            this.keywords = txtKeywords.Text;
            Response.Redirect(searchURL);
        }
        //关健字查询
        protected void btnDetailedSearch_Click(object sender, EventArgs e)
        {
            this.A_Name = txtA_Name.Text;
            this.A_Manager = txtA_Manager.Text;
            Response.Redirect(searchURL);
        }

        //筛选类别
        //设置分页数量
        protected void txtPageNum_TextChanged(object sender, EventArgs e)
        {
            int _pagesize;
            if (int.TryParse(txtPageNum.Text.Trim(), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    Utils.WriteCookie(pageSizeCookieKey, _pagesize.ToString(), 14400);
                }
            }
            Response.Redirect(searchURL);
        }

        #endregion

        #region 删除操作=================================

        //批量删除
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            //检查权限
            //ChkAdminLevel("user_list", ShareMarkingEnums.ActionEnum.Delete.ToString());

            int sucCount = 0;
            int errorCount = 0;
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                int id = Convert.ToInt32(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
                CheckBox cb = (CheckBox)rptList.Items[i].FindControl("chkId");
                if (cb.Checked)
                {
                    if (qr_ActivityService.Instance.Delete_Entity(qr_Activity._.ActivityID == id))
                    {
                        sucCount += 1;
                    }
                    else
                    {
                        errorCount += 1;
                    }
                }
            }

            //记录日志
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除qr_Activity" + sucCount + "条，失败" + errorCount + "条");

            JscriptMsg("删除成功" + sucCount + "条，失败" + errorCount + "条！", searchURL, "Success");
        }

        #endregion

        #region 生成二维码
        public string geturl(string sceneid)
        {
            var qrcode = qr_QrCodeService.Instance.Get_SingleEntity_byWhere(qr_QrCode._.scene_id == sceneid);
            if (qrcode != null)
                return qrcode.qrcode_url;
            return "";
        }
        #endregion

        #region 导出成Excel表格==================

        protected void btnDownload_Click(object sender, EventArgs e)
        {
            int sucCount = 0;
            int errorCount = 0;
            try
            {
                DataSet ds = new DataSet();
                DataTable table = new DataTable();
                string sql = "select qat.A_Name,qat.A_Desc ,qat.A_Manager,qat.A_wxQrCodeID,qat.A_wxSceneID,qat.A_wxTitle,qat.A_wxDesc,qr.qrcode_url from qr_Activity qat  inner join qr_QrCode qr on qat.A_wxSceneID=qr.scene_id";                
                table = DbSession.Default.FromSql(sql).ToTable();
                table.TableName = "qr_Activity";
                ds.Tables.Add(table);

                ExcelExportProvider provider = ExcelExportConfiguration.Current.ExcelConfigs["Activityinfo"];
                // 导入配置文件验证
                ConfigExportValidate(provider, ds, "Activityinfo");
                string fullPath;
                string templateFile = null;
                if (!string.IsNullOrEmpty(templateFile))
                    fullPath = templateFile;
                else if (!string.IsNullOrEmpty(provider.TemplateFile))
                {
                    HttpContext context = HttpContext.Current;
                    if (context != null)
                    {
                        fullPath = context.Server.MapPath("~/" + provider.TemplateFile);
                    }
                    else
                    {
                        fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, provider.TemplateFile);
                    }
                }
                else
                    throw new Exception("参数excelFile及预设的TemplateFile都为空，无法打开Excel文件");

                ExcelUtilities excelUtils = new ExcelUtilities();
                excelUtils.ExportExcel(Response, string.Format("ExportCode_{0}", DateTime.Now.ToString("yyyy-MM-dd")), ds, "Activityinfo");
                sucCount += 1;
            }
            catch (Exception ex)
            {
                //WriteLog.WriteError(ex.ToString());
                ComLib.LogLib.Log4NetBase.Log(ex.Message + ex.StackTrace);
                JscriptMsg("下载时发生错误请联系管理员！", searchURL, "Error");
            }
            //记录日志
            AddAdminLog(DTEnums.ActionEnum.Export.ToString(), "导出NC用户信息" + sucCount + "条，失败" + errorCount + "条");

            JscriptMsg("下载成功" + sucCount + "条，失败" + errorCount + "条！", searchURL, "Success");
        }

        protected void ConfigExportValidate(ExcelExportProvider provider, DataSet container, string typeName)
        {
            ///验证数据容器中是否存在DataTable
            if (container.Tables.Count == 0) throw new Exception("DataSet对象容器中没有任何DataTable对象!");
            ///验证导入配置中的配置节是否存在
            if (provider == null) throw new Exception(string.Format("配置中不存在类型为:{0}的导入配置项!", typeName));
            ///验证配置节中是否包含至少1个worksheet
            if (provider.Worksheets == null || provider.Worksheets.Count == 0) throw new Exception(string.Format("配置中类型为:{0}的配置节中不包含Worksheet的定义", typeName));
            // 验证数据容器中存在配置节中配置的datatable
            foreach (var worksheet in provider.Worksheets)
            {
                foreach (Area area in worksheet.Areas)
                    if (!container.Tables.Contains(area.DataTable))
                        throw new Exception(string.Format("DataTable中不包含表 {0}", area.DataTable));
            }
        }
        #endregion
    }

}